package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-01-29 10:32
 */
public class BackpackIII {
    //前i个物品拼出重量为w时的最大价值
    public int backPackIII(int m, int[] A, int[] V) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int n = A.length;

        int[][] dp = new int[n + 1][m + 1];
        dp[0][0] = 0;
        for (int i = 1; i <= m; i++) {
            //-1表示拼不出来
            dp[0][i] = -1;
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j - A[i - 1] >= 0 && dp[i][j - A[i - 1]] != -1) {
                    dp[i][j] = Math.max(dp[i][j], dp[i][j - A[i - 1]] + V[i - 1]);
                }
            }
        }

        int res = 0;
        for (int i = 0; i <= m; i++) {
            if (dp[n][i] != -1) {
                res = Math.max(res, dp[n][i]);
            }
        }
        return res;
    }

    public int backPackIII2(int m, int[] A, int[] V) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int n = A.length;

        int[] dp = new int[m + 1];
        dp[0] = 0;
        for (int i = 1; i <= m; i++) {
            //-1表示拼不出来
            dp[i] = -1;
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (j - A[i - 1] >= 0 && dp[j - A[i - 1]] != -1) {
                    dp[j] = Math.max(dp[j], dp[j - A[i - 1]] + V[i - 1]);
                }
            }
        }

        int res = 0;
        for (int i = 0; i <= m; i++) {
            if (dp[i] != -1) {
                res = Math.max(res, dp[i]);
            }
        }
        return res;
    }
}
